package com.swz.dcrm.ui.car;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.bumptech.glide.Glide;
import com.nineoldandroids.animation.AnimatorSet;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CarShopCarModelAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarModel;

import com.swz.dcrm.model.Input;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.wrapper.EmptyWrapper;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.util.AnimationUtil;
import com.xh.baselibrary.widget.DrawableEditText;


import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarManagementFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.et_search)
    DrawableEditText etSearch;
    private String searchTag;
    private int page = 1;
    private int size = 15;
    private long total;
    private EmptyWrapper emptyWrapper;
    @Inject
    MainViewModel mainViewModel;
    @Inject
    CarManagementViewModel carManagementViewModel;

    private CarShopCarModelAdapter carShopCarModelAdapter;

    public static CarManagementFragment newInstance() {

        return new CarManagementFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        carManagementViewModel.getCarModel(page, size, searchTag)
                .observe(this, carModelStatePageResponse -> {
                    if (carModelStatePageResponse.isSuccess()) {
                        smartRefreshLayout.setEnableLoadmore(true);
                        total = carModelStatePageResponse.getTotal();

                        if (carShopCarModelAdapter == null) {
                            carShopCarModelAdapter = new CarShopCarModelAdapter(getContext(), carModelStatePageResponse.getData());
                            carShopCarModelAdapter.setOnCollectClickListener(onCollectClickListener);
                            carShopCarModelAdapter.setOnClickListener(carModelStateOnClickListener);
                            emptyWrapper=getEmptyWrapper(carShopCarModelAdapter,R.mipmap.empty_showroom);
                            rv.setAdapter(emptyWrapper);
                        } else {
                            carShopCarModelAdapter.refresh(carModelStatePageResponse.getPage(), carModelStatePageResponse.getData());
                            emptyWrapper.notifyDataSetChanged();
                        }
                    }
                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_electron_office;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        title.setText(getString(R.string.electron_office_title));
        tvRight.setText(getString(R.string.electron_office_car_model));
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.addItemDecoration(new CustomDecoration(getContext(), 5, 5, 10, 10));
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if (carShopCarModelAdapter != null && carShopCarModelAdapter.getItemCount() >= total) {
                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            } else {
                page++;
                onLoadRetry();
            }
        });
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchTag = etSearch.getText().toString().trim();

                    onLoadRetry();
                    mainViewModel.getInput().setValue(new Input(etSearch,0,false));

                return true;
            }
            return false;
        });
        return true;
    }

    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.tv_right)
    public void commonCarModel() {
        go(null, R.id.action_electronOfficeFragment_to_commonCarModelFragment, null);
    }

    OnClickListener<CarModel> carModelStateOnClickListener= carModelState -> {
        CarDetailFragmentArgs.Builder builder=new CarDetailFragmentArgs.Builder();
        builder.setPosition(String.valueOf(carShopCarModelAdapter.getCurrentClickPosition()));
       go(null,R.id.action_electronOfficeFragment_to_carDetailFragment,builder.build().toBundle());
    };

    CarShopCarModelAdapter.OnCollectClickListener onCollectClickListener = (position, imageView) -> {

        carManagementViewModel.collectCarModel(carShopCarModelAdapter.getDatas().get(position).getId())
                .observe(this, carModelStateBaseResponse -> {

                    if (carModelStateBaseResponse.isSuccess() && position ==
                            carShopCarModelAdapter.getCurrentClickPosition()) {
                        imageView.setPivotX(imageView.getWidth()/2);
                        imageView.setPivotY(imageView.getHeight()/2);
                        imageView.animate().scaleX(1.2f).scaleY(1.2f).setDuration(300).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                imageView.setScaleX(1);
                                imageView.setScaleY(1);
                            }
                            @Override
                            public void onAnimationStart(Animator animation) {
                                imageView.setImageResource(R.mipmap.star_active);
                            }
                        }).start();
                    } else {
                        showToast(carModelStateBaseResponse.getMsg());
                    }
                });
    };
}
